import { Button, message, Popconfirm, Space, Spin, Tabs, Tooltip } from 'antd';
import { WorkflowCheckRecordContext } from '../common';
import { useEffect, useMemo, useState } from 'react';
import Cls from 'classnames';

import { WorkflowTimeListView } from './WorkflowTimeListView';
import { DownCircleOutlined, UpCircleOutlined, RollbackOutlined, PlayCircleOutlined, PauseCircleOutlined, ExceptionOutlined } from '@ant-design/icons';

import pageStyles from '@/common/pageLayout.less';
import '../common/styles.less';
import { revokeService, stopProcInstService } from '../services';
import { getColorTextLoadMap, getTenantID, getUserID } from '@/utils';
import { WorkflowCancelModal } from './WorkflowCancelModal';
import { ILoadMapTypeAll } from '@/common';

export const WorkflowChedkRecord: React.FC<WorkflowChedkRecordAPI.IWorkflowChedkRecord> = ({
  curRes,
  dataDetailInfo, // 数据详情
  flowBusinessType, //当前业务流程类别
  requestController, //当前业务Controller
  reloadPageCallback, //刷新页面回调
  revokeStateID, //当前业务初始状态
  allBtnFuncQuqry, // 按钮权限
  tabPaneHeight = 0.4, //tab 页面高度
  isHiddenTabsTitle = false, //是否合并到 tab切换
  isCheckDrawer = false, // 是否展示办理弹框
}) => {
  const prefixCls: string = 'workflow-checkresroot-';

  /**
   * 保存审核信息
   */
  const [taskNodeInfoObj, setTaskNodeInfoObj] = useState<Record<string, any>>({
    activitiTaskHandleList: [], //未办理 的任务
    activitiHisProcinstList: [], //已办理的任务
    flag: null,
  });

  const [allOpenNodeBody, setAllOpenNodeBody] = useState<boolean>(true); //是否展开节点内容

  const [openFlowCancelModal, setOpenFlowCancelModal] = useState<boolean>(false); //是否打开流程作废弹框

  /**
   * 初始化处理流程数据
   */
  useEffect(() => {
    if (dataDetailInfo?.paramObject && JSON.stringify(dataDetailInfo?.paramObject) != '{}') {
      let arr: any = null;
      let paramObject: Record<string, any> = dataDetailInfo?.paramObject;
      for (let k in paramObject) {
        if (k?.endsWith(flowBusinessType)) {
          arr = paramObject[k];
        }
      }
      setTaskNodeInfoObj({
        activitiTaskHandleList: arr ? arr.mactivitiTaskHandleList : [], //未办理 的任务
        activitiHisProcinstList: arr ? arr.mactivitiHisProcinstList : [], //已办理的任务
        flag: arr ? arr.flag : null,
      });
    } else {
      setTaskNodeInfoObj({
        activitiTaskHandleList: [], //未办理 的任务
        activitiHisProcinstList: [], //已办理的任务
        flag: null,
      });
    }
  }, [dataDetailInfo]);

  /**
   * Tab页面
   */
  const tabsPaneItems = useMemo(() => {
    return [
      {
        label: '审批记录',
        key: `${dataDetailInfo?.id}CheckListTabPane`,
        children: <WorkflowTimeListView taskNodeInfoObj={taskNodeInfoObj} />,
      },
    ];
  }, [dataDetailInfo, taskNodeInfoObj]);

  /**
   * 审核撤销回调
   * @param res
   */
  const workflowCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      reloadPageCallback();
    } else {
      message.error(res?.msg);
    }
  };

  /**
   * 引入审核撤销
   */
  const { revokeLoading, revokeRun } = revokeService(workflowCallback, requestController);

  /**
   * 引入挂起流程
   */
  const { stopProcInstLoading, stopProcInstRun } = stopProcInstService(workflowCallback, requestController);

  /**
   * 判断恢复暂停按钮
   */
  const invalidFlagMemo = useMemo(() => {
    const invalBool: boolean = taskNodeInfoObj?.flag?.invalidFlag;
    const invalObj: Record<string, any> = {
      tooltipTitle: invalBool ? '恢复' : '暂停',
      popconTip: invalBool ? '确定恢复审批流程吗？' : '确定暂停审批流程吗？',
      buttonIcon: invalBool ? <PlayCircleOutlined /> : <PauseCircleOutlined />,
    };
    return invalObj;
  }, [taskNodeInfoObj?.flag?.invalidFlag]);

  /**
   * 流程最终审核结果
   */
  const workflowEndResult = useMemo(() => {
    if (taskNodeInfoObj?.activitiHisProcinstList?.length > 0) {
      const checkResultType: string = taskNodeInfoObj?.activitiHisProcinstList[0]?.checkResult;
      let checkResultCls: string = '';
      if (checkResultType?.endsWith('1000') || checkResultType?.endsWith('1001')) {
        checkResultCls = 'infoSgin';
      } else if (checkResultType?.endsWith('1002')) {
        checkResultCls = 'infoSginGreen';
      } else {
        checkResultCls = 'infoSginted';
      }
      const { colorText } = getColorTextLoadMap(taskNodeInfoObj?.activitiHisProcinstList[0].checkResultName);
      return (
        <span
          className={prefixCls + checkResultCls}
          style={{
            top: isHiddenTabsTitle ? '-18px' : '22px',
          }}
        >
          {colorText}
        </span>
      );
    } else {
      return <></>;
    }
  }, [taskNodeInfoObj?.activitiHisProcinstList, isHiddenTabsTitle]);

  /** 审核记录右侧功能操作按钮 */
  const checkOptionBtn = useMemo(() => {
    return (
      <Space size={[8, 0]}>
        {taskNodeInfoObj?.activitiHisProcinstList?.length > 0 && (
          <Tooltip placement="top" title={allOpenNodeBody ? '收起全部' : '展开全部'}>
            <Button
              type="primary"
              icon={allOpenNodeBody ? <UpCircleOutlined /> : <DownCircleOutlined />}
              size="small"
              onClick={() => {
                setAllOpenNodeBody(!allOpenNodeBody);
              }}
              onMouseOut={(event: any) => {
                event?.target?.nodeName == 'BUTTON' ? event?.target?.blur() : event.target.parentNode.blur();
              }}
            />
          </Tooltip>
        )}

        {/* 撤销申请 */}
        {taskNodeInfoObj?.flag && (
          <>
            {curRes[`/${requestController}/revoke`] &&
              allBtnFuncQuqry?.revokeFlagBtn &&
              taskNodeInfoObj?.flag?.revokeFlag &&
              dataDetailInfo?.ownerID == getUserID() && (
                <Tooltip placement="top" title={'撤销'}>
                  <Popconfirm
                    title={<span style={{ fontWeight: 600 }}>确定撤销审批申请吗？</span>}
                    onConfirm={(e: any) => {
                      e?.stopPropagation();
                      const params: Record<string, any> = {
                        id: dataDetailInfo?.id,
                        workflowID: dataDetailInfo?.workflowID,
                        state: revokeStateID,
                      };
                      revokeRun(params);
                    }}
                    okType={'primary'}
                  >
                    <Button
                      type="primary"
                      size="small"
                      icon={<RollbackOutlined />}
                      onMouseOut={(event: any) => {
                        event?.target?.nodeName == 'BUTTON' ? event?.target?.blur() : event.target.parentNode.blur();
                      }}
                    />
                  </Popconfirm>
                </Tooltip>
              )}

            {/* 流程暂停开始 */}
            {allBtnFuncQuqry?.stopProcInstBtn && dataDetailInfo.ownerID == getUserID() && curRes[`/${requestController}/stopProcInst`] && (
              <Tooltip placement="top" title={invalidFlagMemo?.tooltipTitle}>
                <Popconfirm
                  title={<span style={{ fontWeight: 600 }}>{invalidFlagMemo?.popconTip}</span>}
                  onConfirm={(e: any) => {
                    e?.stopPropagation();
                    const params: Record<string, any> = {
                      id: dataDetailInfo?.id,
                      workflowID: dataDetailInfo?.workflowID,
                      paramObject: {
                        procInstID: dataDetailInfo?.workflowID,
                        invalidFlag: taskNodeInfoObj?.flag?.invalidFlag,
                      },
                    };
                    stopProcInstRun(params);
                  }}
                  okType={'primary'}
                >
                  <Button
                    type="primary"
                    size="small"
                    icon={invalidFlagMemo?.buttonIcon}
                    onMouseOut={(event: any) => {
                      event?.target?.nodeName == 'BUTTON' ? event?.target?.blur() : event.target.parentNode.blur();
                    }}
                  />
                </Popconfirm>
              </Tooltip>
            )}
          </>
        )}

        {/* 流程作废 */}
        {curRes[`/${requestController}/invalid`] &&
          allBtnFuncQuqry?.invalBoolBtn &&
          dataDetailInfo.ownerID != getUserID() && ( //当前办理人,且不能是归属人
            <Tooltip placement="top" title={'流程作废'}>
              <Button
                type="primary"
                size="small"
                icon={<ExceptionOutlined />}
                onMouseOut={(event: any) => {
                  event?.target?.nodeName == 'BUTTON' ? event?.target?.blur() : event.target.parentNode.blur();
                }}
                onClick={() => {
                  setOpenFlowCancelModal(true);
                }}
              />
            </Tooltip>
          )}
      </Space>
    );
  }, [curRes, taskNodeInfoObj?.activitiHisProcinstList, taskNodeInfoObj, allOpenNodeBody]);

  return (
    <WorkflowCheckRecordContext.Provider
      value={{
        curRes,
        prefixCls,
        dataDetailInfo,
        requestController,
        reloadPageCallback,
        flowBusinessType,
        revokeStateID,
        allOpenNodeBody,
        isCheckDrawer,
      }}
    >
      <div
        className={'wokk-flow-checdk'}
        style={{
          height: isHiddenTabsTitle ? '100%' : document.body.clientHeight * tabPaneHeight,
          width: '100%',
          position: isHiddenTabsTitle ? undefined : 'relative',
        }}
      >
        {/* 流程审核结果 */}
        {workflowEndResult}

        <Spin spinning={revokeLoading || stopProcInstLoading}>
          <Tabs
            className={Cls([pageStyles['commonTabs'], prefixCls + 'flowTabsClsBox'], {
              'workflow-checkresroot-hiddenTabsTitltSty': isHiddenTabsTitle,
            })}
            type="card"
            items={tabsPaneItems}
            tabBarExtraContent={checkOptionBtn}
          />
        </Spin>

        {/* 显示操作按钮 */}
        {isHiddenTabsTitle && <div className={`${prefixCls}hiddenTabsTitltSty-checkFunctionBtn`}>{checkOptionBtn}</div>}

        {/* 流程作废 */}
        {openFlowCancelModal && (
          <WorkflowCancelModal
            onClose={() => {
              setOpenFlowCancelModal(false);
            }}
            reloadCallback={reloadPageCallback}
            requestController={requestController}
            dataDetailInfo={dataDetailInfo}
            // cancelStateId={`${getTenantID()}${ILoadMapTypeAll.ASSETRRETURN_STATE}1006`}
            cancelStateId={''}
          />
        )}
      </div>
    </WorkflowCheckRecordContext.Provider>
  );
};
